package org.webdb.webapp.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class HttpMethodFilter implements Filter {

    private static final String METHOD_PARAMETER = "__method";

    private HttpServletRequest decorate(HttpServletRequest httpRequest) {
        String method;
        if ((method = httpRequest.getParameter(METHOD_PARAMETER)) != null) {
            method = method.trim().toUpperCase();
            String newMethod = null;

            if ("PUT".equals(method))
                newMethod = "PUT";
            else if ("DELETE".equals(method))
                newMethod = "DELETE";
            else if ("POST".equals(method))
                newMethod = "POST";

            if (newMethod != null) {
                final String mMethod = newMethod;

                httpRequest = new HttpServletRequestWrapper(httpRequest) {
                    @Override
                    public String getMethod() {
                        return mMethod;
                    }

                    @Override
                    public ServletInputStream getInputStream()
                            throws IOException {
                        // TODO Auto-generated method stub
                        return super.getInputStream();
                    }
                };
            }

        }
        return httpRequest;
    }

    private HttpServletResponse decorate(HttpServletResponse httpResponse) {
        return httpResponse;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpRequest = decorate(httpRequest);
        httpResponse = decorate(httpResponse);

        chain.doFilter(httpRequest, httpResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

}
